package com.patent.service.impl;

import com.patent.dao.InvoiceAmountMapper;
import com.patent.domain.po.InvoiceAmount;
import com.patent.service.InvoiceAmountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service("invoiceAmountService")
@Transactional
public class InvoiceAmountServiceImpl implements InvoiceAmountService {

	private static final Logger log = LoggerFactory.getLogger(InvoiceAmountServiceImpl.class);

	@Resource(name="invoiceAmountMapper")
	private InvoiceAmountMapper invoiceAmountMapper;

	@Override
	public void dealInvoiceAmount(String flag, String userMobile, Double orderAmount) {
		try {
			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("userMobile", userMobile);
			InvoiceAmount invoiceAmount = invoiceAmountMapper.selectByMap(queryMap);
			if(invoiceAmount != null){
				BigDecimal amount = invoiceAmount.getAmount();
				if("add".equals(flag)){
					invoiceAmount.setAmount(amount.add(new BigDecimal(orderAmount)));
				}else if("reduce".equals(flag)){
					invoiceAmount.setAmount(amount.subtract(new BigDecimal(orderAmount)));
				}
				invoiceAmountMapper.updateByPrimaryKeySelective(invoiceAmount);
			}else{
				if("add".equals(flag)){
					InvoiceAmount invoiceAmountAdd = new InvoiceAmount();
					invoiceAmountAdd.setUserMobile(userMobile);
					invoiceAmountAdd.setAmount(new BigDecimal(orderAmount));
					invoiceAmountMapper.insertSelective(invoiceAmountAdd);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("处理发票金额表失败：" + e.getMessage());
			throw new RuntimeException(e);
		}
	}

	@Override
	public InvoiceAmount selectByMap(Map<String, Object> map) {
		return invoiceAmountMapper.selectByMap(map);
	}
}
